package com.dream.common.encrypt;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.dream.common.util.Sm4Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import static com.dream.common.constant.CommonConstant.EMPTY;
import static com.dream.common.constant.CommonConstant.SM4_KEY;

/**
 * @description: 国产SM数据加解密接口
 * @author: LiMG
 * @create: 2024-05-20 16:51:35
 **/
@Slf4j
@Service
@ConditionalOnProperty(name = "interface.encrypt.type", havingValue = "sm4")
public class SmEncryptServiceImpl implements IEncryptService {

    /**
     * 数据加密
     * @param data
     * @return
     */
    @Override
    public String encrypt(String data) {
        if (StrUtil.isBlank(data)) {
            return EMPTY;
        }
        try {
            return Sm4Utils.encryptEcb(SM4_KEY, data);
        } catch (Exception e) {
            log.error("数据加密失败：{}", e.getMessage(), e);
            return EMPTY;
        }
    }

    /**
     * 数据解密
     * @param data
     * @return
     */
    @Override
    public String decrypt(String data) {
        if (StrUtil.isBlank(data)) {
            return EMPTY;
        }
        try {
            return Sm4Utils.decryptEcb(SM4_KEY, data);
        } catch (Exception e) {
            log.error("数据解密失败：{}", e.getMessage(), e);
            return EMPTY;
        }
    }

    public static void main(String[] args) {
        String data = "{\"username\":\"111\",\"password\":\"111\",\"email\":\"111\"}";
        String result = Sm4Utils.encryptEcb(SM4_KEY, data);
        System.out.println(result);

        String encryptData = "9cc723317d4371118ca98f3b0a87ced066a699c24d36376c555454824eca60d3cfec669e384d06be181c790347643701bec5d07bec99bf6379f834d2c02a9720bd5b020bba86a83af8ac269ede336634";
        result = Sm4Utils.decryptEcb(SM4_KEY, encryptData);
        System.out.println(result);
    }

}
